<?php

namespace ball\upay;
use GuzzleHttp\Client;
use think\facade\Cache;

/**
 * 收钱吧api
 */
class Upay
{
    protected $apiDomain = 'https://vsi-api.shouqianba.com';
    protected $vendor_sn = '91802546'; //开发序列号
    protected $vendor_key = 'fa988cdf53cb5954067613ff7d054711'; //开发者密钥
    protected $appid = '';
    protected $code = '';
    protected $device_id = '';
    protected $errMsg = '';
    protected int $refreshTokenKeepTime = 86400*15;
    public function __construct()
    {

    }
    /**
     * 激活接口
     */
    public function activate( array $config=[]){
        $url = $this->apiDomain .'/terminal/activate';
        $params = [
            'app_id'    => $this->appid,
            'code'      => $this->code,
            'device_id' => $this->device_id,
        ];
        $params =array_merge($params,$config);
        ksort($params);
        return $this->httpBuild($url,$params,$this->vendor_sn,$this->vendor_key);
    }

    public function httpbuild($url,$params,$sn,$key){
        $sign = MD5(json_encode($params).$key);
        $options=[
            'headers'=>[
                'Content-Type'  => 'application/json',
                "Format"        =>  "json",
                "Authorization" =>$sn." ".$sign,
            ],
            'json' => $params,
        ];
        return $this->http($url,$options);
    }   

    public function http($url,$options=[],$method='POST'){
        try {
            $client = new Client();
            $option = [
                'timeout'         => 30,
                'connect_timeout' => 30,
                'verify'          => false,
                'http_errors'     => true,
                
            ];
            $response = $client->request($method, $url,array_merge($option,$options));
            if($response->getStatusCode() == 200){
                return json_decode($response->getBody()->getContents(),1);
                
            }else{
                return false;
            }
        } catch (\Throwable $th) {
            $this->errMsg = $th->getMessage();
            return false;
        }
    }
}